import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;

public class WeightProtocol {
	private PrintStream out;
	private BufferedReader in;

	public WeightProtocol(PrintStream out, BufferedReader in){
		this.out = out;
		this.in = in;
	}

	public String sendRead(){
		out.println("S");
		String fromServer = null;
		try {
			while ((fromServer = in.readLine()) != null){
				//				logger.write("Server: " + fromServer);
				if(fromServer.contains("S S")){
					return (fromServer.split("S S")[1]);
				}else if(fromServer.contains("ES")){
					return "0 kg";
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fromServer;
	}

	public String sendTare(){
		out.println("T");
		String fromServer = null;
		try {
			while ((fromServer = in.readLine()) != null){
				//				logger.write("Server: " + fromServer);
				if(fromServer.contains("T S ")){
					return (fromServer.split("T S ")[1]);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fromServer;
	}

	public void sendZero(){
		out.println("Z");
	}

	public void sendD(String message){
		out.println("D "+message);
	}

	public void sendDW(){
		out.println("DW");
	}

	public void sendRM30(String[] msg){
		out.println("RM30 \""+msg[0]+"\" \""+msg[1]+"\" \""+msg[2]+"\" \""+msg[3]+"\"");
		out.println("RM39 1");
	}

	public String waitForButton(){
		String fromServer = null;

		try {
			while ((fromServer = in.readLine()) != null){
				//				logger.write("Server: " + fromServer);
				if(fromServer.contains("RM30 C ")){
					return (fromServer.split("RM30 C ")[1]);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fromServer;
	}

	public String sendRM20(String[] msg){
		String Display = " \""+msg[0];
		Display = Display+"\" \""+msg[1];
		Display = Display+"\" \""+msg[2]+"\"";
		//		logger.write("Client: " + "RM20 8"+Display);
		out.println("RM20 8"+Display);
		String fromServer = null;
		try {
			while ((fromServer = in.readLine()) != null){
				//				logger.write("Server: " + fromServer);
				if(fromServer.contains("RM20 A")){
					try {
						String tempFromServer = fromServer.split("RM20 A ")[1];
						return (tempFromServer.split("\"")[1]);
					} catch (IndexOutOfBoundsException e) {
						return null;
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("Lost connection to server");
		System.exit(-1);

		System.out.println(fromServer);
		return fromServer;
	}
}
